//
//  HNSH_IntegralBillViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/1.
//

#import "HNSH_IntegralBillViewController.h"

//view
#import "JXPagerView.h"
#import "JXCategoryTitleView.h"
#import "JXCategoryIndicatorLineView.h"
#import "HNSH_IntegralBillHeader.h"
#import "CGXDatePickerView.h"

#import "HNSH_IntegralBillCell.h"

static NSString * cellString = @"HNSH_IntegralBillCellID";

@interface HNSH_IntegralBillViewController ()
/**  */
@property (nonatomic, strong)HNSH_IntegralBillHeader * headerView;
/**  */
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
/**  */
@property (nonatomic, strong)NSMutableArray * dataArray;
/**  */
@property (nonatomic, assign)NSInteger page;
/**  */
@property (nonatomic, copy)NSString * currentDate;
/**  */
@property (nonatomic, copy)NSString * year;
/**  */
@property (nonatomic, copy)NSString * month;
/**  */
@property (nonatomic, copy)NSString * day;

/* capital_list */
@property (nonatomic, strong) NSArray *capital_list;

@end

@implementation HNSH_IntegralBillViewController

//MARK: Cycle Methods
- (void)viewDidLoad{
    [super viewDidLoad];
    [self configTableView];
}

- (void)configViewWithType:(NSInteger)type zjType:(NSInteger)zjType capital_list:(NSArray *)capital_list {
    _type = type;
    _zjType = zjType;
    _capital_list = capital_list;
    self.headerView.typeBtn.hidden = capital_list.count <= 0;
    for (NSDictionary *dic in self.capital_list) {
        if ([dic[@"type"] integerValue] == _zjType) {
            [self.headerView.typeBtn setTitle:[NSString stringWithFormat:@"%@ ",dic[@"label"]] forState:UIControlStateNormal];
            break;
        }
    }
    [self refreshData:1];
}

- (void)configTableView {
    [self setupRefresh:self.tableView option:ST_RefreshDefault];
    [self setupEmpty:self.tableView image:[UIImage imageNamed:@"empty_list_data"] title:@""];
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.tableView.rowHeight = 60;
    [self.tableView registerClass:[HNSH_IntegralBillCell class] forCellReuseIdentifier:cellString];
    self.tableView.tableHeaderView = self.headerView;
}


#pragma mark networking
- (void)refreshData:(NSInteger)page {
    self.page = page;
    [HNSH_UserNetServer requestBillListWithParams:[self getParams] success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            if (page == 1) {
                [self.dataArray removeAllObjects];
            }
            NSArray * records = responseObject.resultset[@"list"];
            NSArray * array = [NSArray yy_modelArrayWithClass:HNSH_IntegralBillModel.class json:records];
            [self.dataArray addObjectsFromArray:array];
            [self endRefresh:array.count>=10];
            [self.tableView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        [self.tableView reloadData];
        [self.tableView reloadData];
    }];
}

- (NSDictionary *)getParams{
    //accountTypes:资金类型  1       积分    2       汇宝       3       汇豆
    //incomeType:收益类型 0:支出 1:收益 null:全部
    //dateRange:时间范围 0:有时间范围 1:无时间范围
    NSString * incomeType = @"";
    if (self.type == 1) {
        incomeType = @"0";
    }
    if (self.type == 2) {
        incomeType = @"1";
    }
    [self getTime];
    NSDictionary * params = @{@"account_type":[NSString stringWithFormat:@"%ld", self.zjType],
                              @"income_type":incomeType,
                              @"date_range":@"0",
                              @"year":self.year ? : @"",
                              @"month":self.month ? : @"",
                              @"day":self.day ? : @"",
                              @"page_size":@"10",
                              @"page_num":[NSString stringWithFormat:@"%ld", self.page]};
    return params;
}


- (void)getTime{
    if (![self.currentDate isNotBlank]) {
        self.currentDate = [NSString getToday];
    }
    NSArray * array = [self.currentDate componentsSeparatedByString:@"-"];
    if (array.count > 0) {
        self.year = array[0];
    }
    if (array.count > 1) {
        self.month = array[1];
    }
    if (array.count > 2) {
        self.day = array[2];
    }
}

- (void)chooseTime{
    CGXPickerViewManager *manager = [[CGXPickerViewManager alloc]init];
    manager.leftBtnBGColor = [UIColor appGreenColor];
    manager.rightBtnBGColor = [UIColor appGreenColor];
    manager.titleLabelColor = [UIColor appGreenColor];
    manager.leftBtnborderColor = [UIColor appGreenColor];
    manager.rightBtnborderColor = [UIColor appGreenColor];
    manager.pickerTitleColor = [UIColor appBlackLabelColor];
    manager.pickerTitleSelectColor = [UIColor appBlackLabelColor];
    [CGXDatePickerView showDatePickerWithTitle:@"请选择时间" DateType:UIDatePickerModeDate DefaultSelValue:nil MinDateStr:nil MaxDateStr:nil IsAutoSelect:NO ResultBlock:^(NSString *selectValue) {
        self.currentDate = selectValue;
        self.headerView.time = self.currentDate;
        [self.tableView.mj_header beginRefreshing];
    } Manager:manager];
}

- (void)showTypeAlertWithButton:(UIButton *)button {
    if (self.capital_list.count <= 0) {
        return;
    }
    RGB(247, 133, 51);
    WeakSelf(weakSelf);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSDictionary *dic in self.capital_list) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@",dic[@"label"]] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [button setTitle:[NSString stringWithFormat:@"%@ ",dic[@"label"]] forState:UIControlStateNormal];
            NSInteger type = [dic[@"type"] integerValue];
            weakSelf.zjType = type;
            if (weakSelf.typeBlock) {
                weakSelf.typeBlock(type);
            }
            [weakSelf headerRefreshing];
        }];
        [alert addAction:action];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancelAction];
    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:alert animated:YES completion:nil];
}

- (HNSH_IntegralBillHeader *)headerView{
    if (!_headerView) {
        _headerView = [[HNSH_IntegralBillHeader alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 48)];
        
        WeakSelf(weakSelf);
        _headerView.chooseTimeBlock = ^{
            [weakSelf chooseTime];
        };
        _headerView.changeTypeBlock = ^(UIButton * _Nonnull button) {
            [weakSelf showTypeAlertWithButton:button];
        };
    }
    return _headerView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArray;
}

//MARK: UITableViewDelegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HNSH_IntegralBillCell * cell = [tableView dequeueReusableCellWithIdentifier:cellString];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    !self.scrollCallback ?: self.scrollCallback(scrollView);
}

//MARK: JXPagingViewListViewDelegate Methods
- (UIView *)listView{
    return self.view;
}

- (UIScrollView *)listScrollView{
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback{
    self.scrollCallback = callback;
}

- (void)listWillAppear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidAppear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listWillDisappear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidDisappear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

@end
